import 'package:flutter/material.dart';
import 'package:get/get.dart';
import '../../app_views.dart';
import 'profile_state.dart';
import '../../data/models/user_info_model.dart';

/// 个人中心逻辑控制器 - Profile Logic Controller
///
/// 管理个人中心页面的状态和业务逻辑
/// Manages profile page state and business logic
///
/// 基于GetX最新最佳实践实现，提供响应式状态管理
/// Based on GetX latest best practices, providing reactive state management
class ProfileLogic extends GetxController {
  // 响应式状态变量 - Reactive state variables
  final state = ProfileState().obs;

  /// 显示的用户名 - Display name
  /// 根据登录状态和用户信息返回合适的显示名称
  /// Returns appropriate display name based on login status and user info
  String displayName() {
    if (!state.value.isLoggedIn) return '点击登录';
    return state.value.userPhone ??
        state.value.userEmail ??
        '用户$state.value.userId';
  }

  @override
  void onInit() {
    super.onInit();
    // 初始化时加载用户信息 - Load user info on initialization
    _initializeSettingItems();
    loadUserInfo();
  }

  @override
  void onReady() {
    super.onReady();
    // 每次页面显示时刷新用户信息 - Refresh user info when page is shown
    ever(state, (_) => loadUserInfo());
  }

  /// 初始化设置项列表 - Initialize setting items list
  void _initializeSettingItems() {
    final settingItems = [
      SettingItem(
        icon: 'person',
        title: '个人信息',
        subtitle: '查看和编辑个人资料',
        onTap: () => _navigateToPersonalInfo(),
      ),
      SettingItem(
        icon: 'security',
        title: '账号安全',
        subtitle: '密码、验证等安全设置',
        onTap: () => _navigateToSecurity(),
      ),
      SettingItem(
        icon: 'notifications',
        title: '消息通知',
        subtitle: '推送、提醒等通知设置',
        onTap: () => _navigateToNotifications(),
      ),
      SettingItem(
        icon: 'help',
        title: '帮助与反馈',
        subtitle: '常见问题、意见反馈',
        onTap: () => _navigateToHelp(),
      ),
      SettingItem(
        icon: 'info',
        title: '关于我们',
        subtitle: '版本信息、用户协议',
        onTap: () => _navigateToAbout(),
      ),
    ];
    
    state.value.settingItems = settingItems;
  }

  // 导航方法 - Navigation methods
  void _navigateToPersonalInfo() {
    Get.snackbar('提示', '个人信息功能开发中，敬请期待');
  }

  void _navigateToSecurity() {
    Get.snackbar('提示', '账号安全功能开发中，敬请期待');
  }

  void _navigateToNotifications() {
    Get.snackbar('提示', '消息通知功能开发中，敬请期待');
  }

  void _navigateToHelp() {
    Get.snackbar('提示', '帮助与反馈功能开发中，敬请期待');
  }

  void _navigateToAbout() {
    Get.snackbar('提示', '关于我们功能开发中，敬请期待');
  }

  /// 加载用户信息 - Load user information
  Future<void> loadUserInfo() async {
    state.value.isLoading = true;
    
    try {
      // 从本地存储获取用户信息 - Get user info from local storage
      state.value.isLoading = false;
    state.value.errorMessage = null;
    state.value.isLoggedIn = StorageService.to.isLoggedIn;
    state.value.userPhone = StorageService.to.userPhone;
    state.value.userEmail = StorageService.to.userEmail;
    state.value.userId = StorageService.to.userId;
      
      // 如果已登录，获取详细用户信息 - If logged in, get detailed user info
      if (state.value.isLoggedIn) {
        await _loadDetailedUserInfo();
      }
    } catch (e) {
      state.value.isLoading = false;
    state.value.errorMessage = '加载用户信息失败: $e';
      debugPrint('加载用户信息失败: $e');
    }
  }

  /// 加载详细用户信息 - Load detailed user information
  Future<void> _loadDetailedUserInfo() async {
    try {
      // 这里可以调用API获取详细用户信息
      // Here you can call API to get detailed user information
      
      // 模拟用户信息 - Mock user information
      final userInfo = UserInfo(
        id: state.value.userId ?? '',
        phone: state.value.userPhone ?? '',
        email: state.value.userEmail ?? '',
        nickname: '用户${state.value.userId?.substring(0, 6) ?? ''}',
        avatar: '',
        createdAt: DateTime.now().subtract(const Duration(days: 30)),
      );
      
      state.value.userInfo = userInfo;
    } catch (e) {
      debugPrint('加载详细用户信息失败: $e');
    }
  }

  /// 退出登录 - Logout
  Future<void> logout() async {
    try {
      state.value.isLoggingOut = true;
      
      // 清除本地存储的用户信息 - Clear user info from local storage
      await StorageService.to.clearAll();
      
      // 更新状态 - Update state
      state.value.isLoading = false;
    state.value.errorMessage = null;
    state.value.userInfo = null;
    state.value.isLoggedIn = false;
    state.value.isLoggingOut = false;
    state.value.userPhone = null;
    state.value.userEmail = null;
    state.value.userId = null;
      
      // 跳转到登录页面 - Navigate to login page
      Get.offAllNamed('/auth');
      
      Get.snackbar(
        '提示',
        '退出登录成功',
        snackPosition: SnackPosition.TOP,
        backgroundColor: Colors.green,
        colorText: Colors.white,
      );
    } catch (e) {
      state.value.errorMessage = '退出登录失败: $e';
    state.value.isLoggingOut = false;
      debugPrint('退出登录失败: $e');
      
      Get.snackbar(
        '错误',
        '退出登录失败: $e',
        snackPosition: SnackPosition.TOP,
        backgroundColor: Colors.red,
        colorText: Colors.white,
      );
    }
  }

  /// 处理认证操作 - Handle authentication action
  /// 根据登录状态决定是刷新信息还是跳转登录页
  /// Decides whether to refresh info or navigate to login based on login status
  void handleAuthAction() {
    if (state.value.isLoggedIn) {
      // 已登录，刷新用户信息 - Already logged in, refresh user info
      loadUserInfo();
    } else {
      // 未登录，跳转到登录页 - Not logged in, navigate to login page
      Get.toNamed('/auth/login');
    }
  }

  /// 处理设置项点击 - Handle setting item tap
  /// 根据设置项配置执行相应的操作
  /// Executes corresponding action based on setting item configuration
  void onSettingItemTap(SettingItem item) {
    if (item.onTap != null) {
      // 如果有自定义点击处理，执行自定义逻辑 - If has custom tap handler, execute custom logic
      item.onTap!();
    } else if (item.route != null && item.route!.isNotEmpty) {
      // 如果有路由，跳转到对应页面 - If has route, navigate to corresponding page
      Get.toNamed(item.route!);
    } else {
      // 默认显示开发中提示 - Default show under development message
      Get.snackbar(
        item.title ?? '功能',
        '功能开发中，敬请期待',
        backgroundColor: Colors.orange,
        colorText: Colors.white,
        duration: const Duration(seconds: 2),
      );
    }
  }

  /// 刷新页面数据 - Refresh page data
  Future<void> refresh() async {
    loadUserInfo();
  }
}
